package com.compty.paint.web.front;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import net.sf.json.JSONArray;

import com.compty.core.framework.util.StringUtil;
import com.compty.core.struts2.BaseAction;
import com.compty.core.utils.CommonsUtil;
import com.compty.paint.domain.BackgroundImage;
import com.compty.paint.domain.CatalogType;
import com.compty.paint.domain.Painter;
import com.compty.paint.domain.Painting;
import com.compty.paint.manager.BackgroundImageManager;
import com.compty.paint.manager.PainterManager;
import com.compty.paint.manager.PaintingManager;
import com.compty.paint.util.ImageUtil;

/**
 * @Todo:摆设效果前台显示
 * @CreateTime:2011-7-15 下午06:18:46
 */
public class BackgroundAction extends BaseAction<BackgroundImage>{

	private static final long serialVersionUID = 7552150626022199869L;
	
	private Painting painting;
	private BackgroundImageManager backgroundImageManager;
	private PaintingManager paintingManager;
	private PainterManager painterManager;
	
	/**
	 *@throws Exception 
	 * @Todo:显示摆设效果
	 *@CreateTime:2011-7-15 上午11:40:26
	 */
	@SuppressWarnings("unchecked")
	public String showEffect() throws Exception{
		
	    	String  idStr = request.getParameter("id");
	    	if( !StringUtil.isDigit(idStr) ){
	    		return ERROR;
	    	}
			this.painting = paintingManager.get(Long.valueOf(idStr));
			
			List<BackgroundImage> backgroundImageList = backgroundImageManager.findBackgroundImagesByPainting(painting);
			if( backgroundImageList == null){
				request.setAttribute("ajaxData", "[]");
				request.setAttribute("backimgsList", new ArrayList());
				request.setAttribute("errorMessage", "该作品缺少参数，不能生成预览效果图");
				return "showEffects" ;
			}
			
			List<Map> returnList = new ArrayList<Map>();
			List<String> backimgsList = new ArrayList<String>();
			for (BackgroundImage backgroundImage : backgroundImageList) {
				
				writePaintingImageOfBackground(painting, backgroundImage);
				
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("id", backgroundImage.getId());
				map.put("title", backgroundImage.getTitle());
				map.put("imageid", backgroundImage.getImageInfo().getId());
				map.put("suffix", backgroundImage.getImageInfo().getSuffix());
				map.put("position", backgroundImage.getPosition());
				returnList.add(map);
				
				String back_img_url = painting.getImageInfo().getId()+"_" + backgroundImage.getId()+"_back."+painting.getImageInfo().getSuffix();
				backimgsList.add(back_img_url);
			}
			
			String  ajaxData = JSONArray.fromObject(returnList).toString();
			request.setAttribute("ajaxData", ajaxData);
			request.setAttribute("backimgsList", backimgsList);
			
			CatalogType catalogType  = painting.getCatalogType();
			if( catalogType != null){
				if("国画".equals(catalogType.getName())){
					return "showEffects_guohua";
				}
			}
		
		return "showEffects" ;
	}
	
	/**
	 * 显示作品详情(仅名画作品采用原有展示页面，其他作品均采用瓷艺频道展示页面)
	 *@CreateTime:2011-7-15 下午04:49:15
	 */
	public String showDetail(){
		
    	String  idStr = request.getParameter("id");
    	if( !StringUtil.isDigit(idStr) ){
    		return ERROR;
    	}
			
		this.painting = paintingManager.get(Long.valueOf(idStr));
		
		Painter painter = painting.getPainter();
		if( painter != null ){
			
			String painter_type = painter.getType();
			if("2".equals(painter_type)){
				return "jumptoPaintingDetailOfPainterStar";
			}
			
		}
		
		return "jumptoCiyiDetail";
	}
	
	/**
	 *@Todo:显示名画名家作品详情
	 *@CreateTime:2011-8-25 上午10:39:49
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String showPaintingDetailOfPainterStar(){
		
			
	    	String  idStr = request.getParameter("id");
	    	if( !StringUtil.isDigit(idStr) ){
	    		return ERROR;
	    	}
			
			this.painting = paintingManager.get(Long.valueOf(idStr));
			Painter painter = painting.getPainter();
			
			List<Painter> painterList = painterManager.findPaintersByDecade(painter.getDecade());
			List<Map> painterReturnList = new ArrayList<Map>();
			for (Painter p : painterList) {
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("id", p.getId());
				map.put("imageid", p.getImageInfo().getId());
				map.put("suffix", p.getImageInfo().getSuffix());
				map.put("smallImagePath", p.getSmallImagePath());
				map.put("painter_name", p.getName());
				if( p.getNewestIndex() != null){
					map.put("newIndex", p.getNewestIndex().getTime_period()+"&nbsp;&nbsp;均价"+p.getNewestIndex().getPrice());
				}else{
					map.put("newIndex","&nbsp;&nbsp;均价&nbsp;&nbsp;");
				}
				if(p.getMaxIndex() != null){
					map.put("maxIndex", p.getMaxIndex().getTime_period()+"&nbsp;&nbsp;均价"+p.getMaxIndex().getPrice());	
				}else{
					map.put("maxIndex","&nbsp;&nbsp;均价&nbsp;&nbsp;");
				}
				if( p.getMinIndex() != null){
					map.put("minIndex", p.getMinIndex().getTime_period()+"&nbsp;&nbsp;均价"+p.getMinIndex().getPrice());
				}else{
					map.put("minIndex","&nbsp;&nbsp;均价&nbsp;&nbsp;");
				}
				painterReturnList.add(map);
			}
			
			String  ajaxData_painterList = JSONArray.fromObject(painterReturnList).toString();
			request.setAttribute("ajaxData_painterList", ajaxData_painterList);
			
			Long painter_id = painter.getId();
			List<Painting> paintingList  = paintingManager.findAvailablePaintingsByPainter(painter_id);
			
			List<Map> returnList = new ArrayList<Map>();
			for (Painting painting : paintingList) {
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("id", painting.getId());
				map.put("title", painting.getTitle());
				map.put("painterId", painting.getPainter().getId());
				map.put("painter_name", painting.getPainter().getName());
				map.put("imageid", painting.getImageInfo().getId());
				map.put("suffix", painting.getImageInfo().getSuffix());
				map.put("originalImagePath", painting.getOriginalImagePath());
				map.put("smallImagePath", painting.getSmallImagePath());
				if(painting.getEntryPerson() != null){
					map.put("provider", painting.getEntryPerson().getUsername());
				}else{
					map.put("provider", "");
				}
				returnList.add(map);
			}
			
			String  ajaxData = JSONArray.fromObject(returnList).toString();
			request.setAttribute("ajaxData", ajaxData);
		
		return "showPaintingDetailOfPainterStar";
	}
	
    /**
     *@Todo:为图片生成匹配背景的图片
     *@CreateTime:2011-11-24 下午05:06:25
     * @param painting 作品
     * @param backgroundImage 背景
     * @throws Exception
     */
    protected void writePaintingImageOfBackground(Painting painting,BackgroundImage backgroundImage) throws Exception{
    	
//    	if(backImgMap.containsKey(painting.getId()+"_"+backgroundImage.getId())){
//    		return;
//    	}
//    	backImgMap.put(painting.getId()+"_"+backgroundImage.getId(),String.valueOf(painting.getId()));
    	
    	float width_painting = painting.getWidth();
		float height_painting = painting.getHight();
		Long sharpId = painting.getSharpInfo().getId();
		
		long image_id = painting.getImageInfo().getId();
		String suffix = painting.getImageInfo().getSuffix();
		
		String imageAbsolutePathPrefix = getImageGeneratePath();
		
		String imgPath = imageAbsolutePathPrefix +CommonsUtil.getPathSymbol()+ "painting" + CommonsUtil.getPathSymbol()+ image_id +"."+ suffix;
		
		File f = new File(imgPath);
		BufferedImage sourceImage = ImageIO.read(f);
		int prevW = sourceImage.getWidth();
        int prevH = sourceImage.getHeight();
		
		String painting_back = imageAbsolutePathPrefix+CommonsUtil.getPathSymbol()+ "painting" + CommonsUtil.getPathSymbol()+ image_id +"_"+backgroundImage.getId() +"_back."+ suffix ;
		
		double ratio = 0.0;	//后置比例
		double prep_ratio = 0.0;	//前置比例
		
		double real_pc_width  = width_painting*0.4 ;//实际PC尺寸
		double real_pc_height  = height_painting*0.4 ;//实际PC尺寸
		double virtual_pc_width = (prevW*2.54)/72;  //图片对应的PC虚拟尺寸
		if(sharpId == 3){
			prep_ratio = real_pc_width / virtual_pc_width ;//前置比例
		}else{
			double virtual_pc_height= prevH*2.54/72;
			prep_ratio = real_pc_height / virtual_pc_height ;//前置比例
		}
		
		String  size_horizontal = backgroundImage.getSize_horizontal();
		String size_vertical = backgroundImage.getSize_vertical();
		String size_square = backgroundImage.getSize_square();
		
		if( sharpId == 1 ){//正方形
			if("1".equals(size_square)){
				ratio = 0.58;
			}
			else if("2".equals(size_square)){
				ratio = 0.30;
			}
			else if("3".equals(size_square)){
				ratio = 0.25;
			}
			else if("4".equals(size_square)){
				ratio = 0.20;
			}
			else if("5".equals(size_square)){
				ratio = 0.18;
			}
			else if("6".equals(size_square)){
				ratio = 0.17;
			}
			else if("7".equals(size_square)){
				ratio = 0.15;
			}
		}
		else if(sharpId == 2){//长方形(竖)
			if("1".equals(size_vertical)){
				ratio = 0.58;
			}
			else if("2".equals(size_vertical)){
				ratio = 0.30;
			}
			else if("3".equals(size_vertical)){
				ratio = 0.25;
			}
			else if("4".equals(size_vertical)){
				ratio = 0.20;
			}
			else if("5".equals(size_vertical)){
				ratio = 0.18;
			}
			else if("6".equals(size_vertical)){
				ratio = 0.17;
			}
			else if("7".equals(size_vertical)){
				ratio = 0.15;
			}
		}
		else if( sharpId == 3 ){//长方形(横)
			if("1".equals(size_horizontal)){
				ratio = 0.7;
			}
			else if("2".equals(size_horizontal)){
				ratio = 0.4;
			}
			else if("3".equals(size_horizontal)){
				ratio = 0.23;
			}
			else if("4".equals(size_horizontal)){
				ratio = 0.17;
			}
			else if("5".equals(size_horizontal)){
				ratio = 0.14;
			}
			else if("6".equals(size_horizontal)){
				ratio = 0.12;
			}
		}
		
		ratio = prep_ratio * ratio;
	
		int targetWidth = (int)(prevW * ratio);
		int targetHeight = (int)(prevH * ratio);
		ImageUtil.resize(imgPath,painting_back, targetWidth, targetHeight);
    }

	public void setBackgroundImageManager(BackgroundImageManager backgroundImageManager) {
		this.backgroundImageManager = backgroundImageManager;
	}

	public void setPaintingManager(PaintingManager paintingManager) {
		this.paintingManager = paintingManager;
	}

	public Painting getPainting() {
		return painting;
	}

	public void setPainting(Painting painting) {
		this.painting = painting;
	}

	public void setPainterManager(PainterManager painterManager) {
		this.painterManager = painterManager;
	}
}
